#include "FoGGEDEF.h"
#include ".\tcpsocket.h"

namespace _FOGGE_
{

	namespace _NET_
	{

		TCPSocket::TCPSocket(void)
		{
		}

		TCPSocket::~TCPSocket(void)
		{
		}

		void TCPSocket::CreateSocket()
		{
			CloseSocket();

			m_hSocket=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
		}

		


		int TCPSocket::SendData(char* data,int size)
		{
			assert(m_hSocket != INVALID_SOCKET);
			assert(m_State==eSS_ConnectedByClient||m_State==eSS_HasBeenConnected);
			return send(m_hSocket, data, size, 0);
			
		}
		int TCPSocket::RecvData(LPWSABUF ptrBuffer)
		{
			assert(m_hSocket != INVALID_SOCKET);
			assert(m_State==eSS_ConnectedByClient||m_State==eSS_HasBeenConnected);
		
			DWORD receiveLen, flags = 0;
			SOCKADDR_IN     fromAddr;
			int             fromLen, wsaError;
			if (WSARecv(m_hSocket,
				ptrBuffer,
				(DWORD) 1,
				& receiveLen,
				& flags,
				NULL,
				NULL) == SOCKET_ERROR )
			{

				wsaError = WSAGetLastError();
				if( wsaError == WSAEWOULDBLOCK || wsaError == WSAECONNRESET ) 
				{   // retry
					Sleep( 5 );
					return 0;
				}
				if (flags & MSG_OOB) // this is obb message!!
					return 0;

				assert(!"TCPSocket::RecvData - RecvData error ");
				return 0;
			}
			return receiveLen;
		}
	}
}